import packet_data_types
import json

def ping(payload):
    packet = bytearray()

    packet += packet_data_types.var_int(0x01)  # PID
    packet += payload.to_bytes(8, "little")  # Payload

    packet = packet_data_types.var_int(len(packet)) + packet  # Length

    return packet


def handshake(protocol_version, ip, port, next_state):
    packet = bytearray()

    packet += packet_data_types.var_int(0x0)  # PID
    packet += packet_data_types.var_int(protocol_version)  # Protocol Version
    packet += packet_data_types.string(ip)  # Server Address
    packet += port.to_bytes(2, "little")  # Server Port
    packet += packet_data_types.var_int(next_state)  # Next State

    packet = packet_data_types.var_int(len(packet)) + packet  # Length
    
    return packet


def status():
    packet = bytearray()

    packet += packet_data_types.var_int(0x0) # PID
    
    packet = packet_data_types.var_int(len(packet)) + packet
    
    return packet


def read_packet(s):
    # Read packet length
    packet_bytes = bytearray()
    l = 0
    position = 0

    while True:
        current_byte = s.recv(1)[0]
        l |= (current_byte & packet_data_types.SEGMENT_BITS) << position 
        
        if (current_byte & packet_data_types.CONTINUE_BIT) == 0: break
            
        position += 7
    
    while len(packet_bytes) < l:
        packet_bytes += s.recv(1024)

    return packet_bytes 



def parse_status(bytes):
    total_offset = 0

    packet_id, br = packet_data_types.read_var_int(bytes[total_offset:])
    total_offset += br

    json_data, _ = packet_data_types.read_string(bytes[total_offset:])

    return json.loads(json_data)


def parse_server_description(desc_json):
    res = desc_json["text"] 
    
    if "extra" in desc_json:
        for extra in desc_json["extra"]:
            res += parse_server_description(extra)
    
    return res.strip().replace("\n", " ")